package losrebellos.media.cuepoint.cc 
{
	import losrebellos.media.cuepoint.net.MediaControllerCuePointManager;
	import losrebellos.media.cuepoint.parsers.OvpDfxpParser;
	import losrebellos.projects.mediaplayer.media.base.controller.IMediaController;

	import org.openvideoplayer.events.OvpEvent;

	/*
	 *
	 * @author los rebellos - ben@benoitvinay.com
	 *
	 */
	public class MediaControllerCCManager extends MediaControllerCuePointManager implements ICCManager 
	{
		/*
		 *
		 * VARIABLES
		 *
		 */
		private var _parser:OvpDfxpParser;

		
		/*
		 *
		 * CONSTRUCTOR
		 *
		 */
		public function MediaControllerCCManager(media:IMediaController)
		{
			super(media, false);
			
			_parser = new OvpDfxpParser();
			_parser.addEventListener(OvpEvent.ERROR, onParseError);
			_parser.addEventListener(OvpEvent.PARSED, onParsed);
			
			if(media) 
			{
				this.mediaController = media;
			}
		}
		
		
		/*
		 * 
		 * PROPERTIES
		 * 
		 */
		override public function set mediaController(value:IMediaController):void 
		{
			if(value) 
			{
				super.mediaController = value;
				value.addEventListener(OvpEvent.NETSTREAM_CUEPOINT, onCuePoint);
			}
		}
		
		
		/*
		 * 
		 * XML
		 * 
		 */
		public function load(dfxpURL:String):void
		{
			_parser.load(dfxpURL);
		}
		public function parse(xml:XML):void
		{
			_parser.parse(xml);
		}
		private function onParseError(e:OvpEvent):void 
		{
			dispatchEvent(e);
		}
		private function onParsed(e:OvpEvent):void 
		{
			for (var i:uint = 0;i < _parser.cuePointObjectCount();i++) 
			{
				this.addCuePoint(_parser.cuePointObjectAt(i));
			}
			this.dispatchEvent(e.clone());
		}

		
		/*
		 * 
		 * CUE POINTS
		 * 
		 */
		private function onCuePoint(e:OvpEvent):void
		{
			if(e.data && e.data["name"])
			{
				var name:String = e.data["name"];
				if(name.search(OvpDfxpParser._CC_CUE_POINT_NAME_PREFIX_) == 0)
				{
					dispatchEvent(new OvpEvent(OvpEvent.CAPTION, _parser.captionObjectAt(e.data["id"])));
				}
			}
		}
	}
}